<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/23
 * Time: 2:53 PM
 */
namespace app\common\models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use app\common\exceptions\BizException;
use app\common\traits\ValidatorTrait;
use app\common\traits\ReplaceableModelTrait;
use Illuminate\Foundation\Validation\ValidatesRequests;

/**
 * Class BaseModel
 * @package app\common\models
 * @method static self site()
 * @method static Collection get()
 * @method static self find(string $id)
 * @method static self first()
 * @method static self select(...$fields)
 * @method static self where(...$where)
 * @method static self whereNot(...$where)
 * @method static self orWhere(...$where)
 * @method static self whereBetween(array $where)
 * @method static self with($with)
 * @method static self whereIn($attribute, ...$where)
 * @method static self whereNotIn(...$where)
 * @method static self whereHas(...$where)
 * @method static self insert()
 * @method static self update()
 * @method static self delete()
 *
 */
class BaseModel extends Model
{
    const STATUS_NORMAL = 1;//正常状态常量
    const STATUS_BAN = 0;//禁用/关闭状态常量

    const STATUS_YES = 1;//状态：是
    const STATUS_NO = 0;//状态：否

    const PAGE_SIZE = 10;//分页默认每页数量

   /* protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];*/

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }
    use ValidatorTrait;
    use ValidatesRequests;
    use ReplaceableModelTrait;
    /**
     * 后台全局筛选统一账号scope
     * 预留，暂时不实现
     * @param Builder $query
     * @return $this|Builder
     */
    public function scopeSite(Builder $query)
    {
        return $query;
    }
    /**
     * 校验参数
     * @param $request
     * @param array $rules
     * @param array $messages
     * @param array $customAttributes
     * @throws BizException
     */
    public function validate($request, array $rules, array $messages = [], array $customAttributes = [])
    {
        $validator = $this->getValidationFactory()->make($request, $rules, $messages, $customAttributes);
        //$validator->errors();

        if ($validator->fails()) {
            throw new BizException($validator->errors()->first());
        }
    }
    /**
     * 获取当前时间
     *
     * @return int
     */
    public function freshTimestamp()
    {
        return time();
    }

    /**
     * 避免转换时间戳为时间字符串
     *
     * @param \DateTime|int $value
     * @return \DateTime|int
     */
    public function fromDateTime($value)
    {
        return $value;
    }
}